from django.shortcuts import render
# from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View
from alipay import AliPay
import os
from django import http

from meiduo_01.utils.views import LoginRequiredJsonMixin
from django.conf import settings
from orders.models import OrderInfo
from meiduo_01.utils.response_code import RETCODE
from .models import Payment
# Create your views here.


class PaymentStatusView(LoginRequiredJsonMixin, View):
    """保存订单的订单状态"""

    def get(self, req):
        # 获取到所有的查询字符串参数
        query_dict = req.GET

        # 将查询字符串的类型转成标准的字典类型
        data = query_dict.dict()
        # 从查询字符串参数中，提取并移除 sign， 不能参与签名验证
        signature = data.pop()

        # 创建SDK
        alipay = AliPay(  # 传入公共参数（）对接热任何接口都要传递
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url， 如果采用同步通知就不传
            # 应用私钥和支付宝公钥的路径
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",  # 指定加密标准
            debug=settings.ALIPAY_DEBUG  # 指定是否为开发环境
        )
        # TODO [不太懂]使用SDK对象，调用验证接口函数，得到验证结果
        success = alipay.verify(data, signature)

        if success:
            # 美多商城维护的订单ID
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 修改订单状态，由'待支付'修改为'待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])

            # 响应结果
            context = {
                'trade_id': trade_id
            }

            return render(req, 'pay_success.html')
        else:
            return http.HttpResponseForbidden('非法请求')



        # 如果通过验证，需要将支付宝的支付状态进行处理（*）

        pass

    pass

"""http://www.meiduo.site:8000/payment/status/
?charset=utf-8
&out_trade_no=20191129205814000000009 # 美多商城的订单id
&method=alipay.trade.page.pay.return
&total_amount=7010.00
# sign：确保安全回调
&sign=D%2Fa6aexu7h2lM9EgmaO2m2MXEHQy7FkIcAtlkdt9FgNZ2NdYtnY7Ti%2FE2Vz0XhoX%2FkpzSA43v%2FXsSV5buM3DSqUSgBe7wRSFvytDL9QQdYxTLmmQin46k4n4XflQPji%2BrAgR%2FXAhj84S8w1xuzpSYP6eWwJsQQxRdgDjEAv6FKc74wu3HjiCrMSRFo6D%2Bwdyxeg2yFphtXvD6PLclBkdPHmsI4%2F%2FT1yfG92faEfM6QBzYQVKSJUxJdY%2F51D4kqtWutZN2vR1P8jPryeRyQjXh%2BblHHeFVR6N1QIa7SUwVwW0GYrQh6B9CwIc7qSOOLiOqvXNCVTLCO%2FsUEDBRJXGsg%3D%3D
&trade_no=2019112922001400851000023574  # 支付宝保存的订单id
&auth_app_id=2016101500693584&version=1.0
&app_id=2016101500693584&sign_type=RSA2
&seller_id=2088102179711669&timestamp=2019-11-29+21%3A00%3A40"""


class PaymentView(LoginRequiredJsonMixin, View):
    """订单支付功能"""
    def get(self, req, order_id):
        """
        :param order_id: 需要支付的订单编号
        :return: Json
        """
        # 接收参数，同步校验参数
        user = req.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单信息错误')

        # 创建对接支付宝接口的SDK对象，
        alipay = AliPay(  # 传入公共参数（）对接热任何接口都要传递
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url， 如果采用同步通知就不传
            # 应用私钥和支付宝公钥的路径
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem"),
            sign_type="RSA2",  # 指定加密标准
            debug=settings.ALIPAY_DEBUG  # 指定是否为开发环境
        )

        # SDK对象对接支付宝支付的接口，得到登录页的地址
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,  # 订单标题
            return_url=settings.ALIPAY_RETURN_URL,  # 同步通知的回调地址，如果不是同步通知，就不传
        )

        # 拼接完整的支付宝登录页地址
        # alipay_url = settings.ALIPAY_URL + '?' + order_id
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


